﻿import { Component, ElementRef, Injector, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { HostDashboardData, HostDashboardServiceProxy, ChartDateInterval, NumberOfSummary, NumberOfProcess, StatisticsServiceProxy, KeyValuePairOfStringAndInt32, GetAllRequestOutput, GetRecentlyDeliveryOutput, GetLineInstanceForExecuteOutput, GetReturnAndScrapGroupByModelOutput, WorkingTeamProportion, WorkingTeamServiceProxy, WorkingTeamDto, GetAllInfoOfWorkingTeamsOutput } from '@shared/service-proxies/service-proxies';
import * as moment from 'moment';
import * as _ from 'lodash';
import { Table } from 'primeng/components/table/table';
import { Router } from '@angular/router';
import { MenubarModule } from 'primeng/primeng';
import { resource } from 'selenium-webdriver/http';

@Component({
    templateUrl: './host-dashboard.component.html',
    styleUrls: ['./host-dashboard.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class HostDashboardComponent extends AppComponentBase implements OnInit {
    @ViewChild('EditionStatisticsChart') editionStatisticsChart: ElementRef;
    @ViewChild('IncomeStatisticsChart') incomeStatisticsChart: ElementRef;

    @ViewChild('RecentTenantsTable') recentTenantsTable: Table;
    @ViewChild('ExpiringTenantsTable') expiringTenantsTable: Table;


    numberOfSummary :NumberOfSummary = new NumberOfSummary();
    numberOfModel :KeyValuePairOfStringAndInt32[] = [];
    numberOfProcess : NumberOfProcess[] = [];
    requestions :GetAllRequestOutput[] = [];
    recentlyDeliverys :GetRecentlyDeliveryOutput[] = [];
    lineInstanceForExecuteOrderByDuration:GetLineInstanceForExecuteOutput[] = [];
    lineInstanceForExecuteOrderByDurationCount = 0;
    returnAndScrapGroupByModelOutput :GetReturnAndScrapGroupByModelOutput[] = [];
    workTeamList :WorkingTeamDto[] = [];
    workTeamInfo :GetAllInfoOfWorkingTeamsOutput[] = [];
    filterWorkTeamInfo :GetAllInfoOfWorkingTeamsOutput[] = [];

    currentTime = Date.now();

    data: any;   
    dataOption : any;

    loading = false;
    loadingIncomeStatistics = false;
    isInitialized: boolean;
    hostDashboardData: HostDashboardData;
    currency = '$';
    appIncomeStatisticsDateInterval = ChartDateInterval;
    selectedIncomeStatisticsDateInterval: number;

    editionStatisticsHasData = false;
    incomeStatisticsHasData = false;

    incomeStatisticsData: any = [];
    editionStatisticsData: any = [];

    selectedDateRange: Date[] = [moment().add(-7, 'days').startOf('day').toDate(), moment().endOf('day').toDate()];

    expiringTenantsData = [];
    recentTenantsData = [];

    constructor(
        injector: Injector,
        private _hostDashboardService: HostDashboardServiceProxy,
        private _statisticsService: StatisticsServiceProxy,
        private _workingTeamServiceProxy: WorkingTeamServiceProxy,
        private router: Router   
    ) {
        super(injector);
    
            
    }

    openProcess(model:string,stationName:string,state:string)
    {
        this.router.navigate(['app/duct/process'],{
            queryParams: {
              model: model,
              station: stationName,
              state:state
            }
        });
    }

    init(): void {
        this.selectedIncomeStatisticsDateInterval = ChartDateInterval.Daily;
        this.getDashboardStatisticsData(this.selectedDateRange);
    }

    ngOnInit(): void {
        this.init();
        this.getSummary();
        this.getSummaryForModel();
        this.getSummaryForProcess();
        this.getRecentlyRequestion();
        this.getDelivery();
        this.getDecadeLineInstanceOrderByDuration();
        this.getReturnAndScrapGroupByModel();
        this.getAllWorkTeam();
        this.getAllInfoOfWorkingTeams();
    }

    getFilterWorkTeamInfo(workTeamId: number)
    {
        console.log(workTeamId.toString());
        this.filterWorkTeamInfo = this.workTeamInfo.filter(c=>c.workingTeamId !== workTeamId);
    }

    getAllInfoOfWorkingTeams()
    {
        let stationIdArray = [2,10,5,6];
        this._statisticsService.getAllInfoOfWorkingTeams(6,stationIdArray).subscribe((result)=>
            {
                this.workTeamInfo = result;
                this.getFilterWorkTeamInfo(this.workTeamList[0].id);
            }
        );

    }

    getAllWorkTeam()
    {
            this._workingTeamServiceProxy.getAll(
                '','','',0,100
            ).subscribe((result)=>
            {
                this.workTeamList = result.items;
                    console.log('工位'+this.workTeamList.length);
            })
    }


    getReturnAndScrapGroupByModel()
    {

        this._statisticsService.getReturnAndScrapGroupByModel(
        ).subscribe((result)=>
        {
            this.returnAndScrapGroupByModelOutput = result;
        });
    }

    getDecadeLineInstanceOrderByDuration()
    {
        let skipCount = 0;      

        if (( this.lineInstanceForExecuteOrderByDuration.length % 10)!==0)
        {
            return;
        }

       if(this.lineInstanceForExecuteOrderByDuration.length == 0 || this.lineInstanceForExecuteOrderByDuration == null) 
        {
            skipCount =  0;
        }    
        else
        {  
            skipCount =  this.lineInstanceForExecuteOrderByDuration.length;
        }

        this._statisticsService.getAllLineInstanceOrderByDuration(
            '','','','','','',10,skipCount
        ).subscribe((result)=>
        {          
            let instances = result.items;
            instances.forEach(element => {
                this.lineInstanceForExecuteOrderByDuration.push(element);
            });
            this.lineInstanceForExecuteOrderByDurationCount = result.totalCount-this.lineInstanceForExecuteOrderByDuration.length;
        });
    }

    getDelivery()
    {
        this._statisticsService.getRecentlyDelivery(10).subscribe((result)=>
        {
            this.recentlyDeliverys = result;
        });

    }

    getSummary()
    {
        this._statisticsService.getSummary().subscribe((result)=>
        {
            this.numberOfSummary = result;
        });

    }

    getSummaryForModel()
    {
        this._statisticsService.getSummaryForModel().subscribe((result)=>
        {
            this.numberOfModel = result;

            let numbers = [];
            this.numberOfModel.forEach(element => {
                numbers.push(element.value);
            });

            let models = [];
            this.numberOfModel.forEach(element => {
                models.push(element.key);
            });

            this.data = {
                labels: models,
                datasets: [
                    {
                        data: numbers,
                        backgroundColor: [
                            "#FF6384",
                            "#36A2EB",
                            "#FFCE56",
                            "#66ff66",
                            "#0099ff",
                            "#990033",
                            "#ffcc66",
                            "#669900",
                            "#3333ff",
                            "#9900ff",
                            "#ff6699",

                        ],
                        hoverBackgroundColor: [
                            "#FF6384",
                            "#36A2EB",
                            "#FFCE56",
                            "#66ff66",
                            "#0099ff",
                            "#990033",
                            "#ffcc66",
                            "#669900",
                            "#3333ff",
                            "#9900ff",
                            "#ff6699",
                        ]
                    }],
               
                };
                this.dataOption = {
                    rotation : Math.PI,
                    circumference: Math.PI,
                    responsive: true,
                    legend: {
                        display: true,
                        position: 'bottom',
                    },
                    title: {
                        display: false,
                        text: 'Chart.js Doughnut Chart'
                    },
                    animation: {
                        animateScale: true,
                        animateRotate: true
                    }
                }
        });

    }

    getRecentlyRequestion()
    {
        this._statisticsService.getRecentlyRequestion().subscribe((result)=>
        {
            this.requestions = result;
        });
    }

    getSummaryForProcess(){

        this._statisticsService.getSummaryForProcess().subscribe((result)=>
        {
            this.numberOfProcess = result;
        });
    }

    getDashboardStatisticsData(dates: any): void {

      
    }

    /*
    * Edition statistics pie chart
    */

    normalizeEditionStatisticsData(data): Array<any> {
        const chartData = new Array(data.length);



        return chartData;
    }

    /*
     * Income statistics line chart
     */


    normalizeIncomeStatisticsData(data): any {
       
    }

    incomeStatisticsDateIntervalChange(interval: number) {
       
    }

    refreshIncomeStatisticsData(): void {
       
    }

    gotoAllRecentTenants(): void {
      
    }

    gotoAllExpiringTenants(): void {
       
    }
}
